import axios from "axios";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken, serverUrl } from "./tools";

const instance = axios.create({
  baseURL: serverUrl, // 网络请求的基础地址
  timeout: 5000, // 超时时间
});

// Add a request interceptor
// 全局请求拦截
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    // 此处可以添加请求头
    NProgress.start(); // 启动进度条
    config.headers.token = getToken();
    return config;
  },
  function (error) {
    // Do something with request error
    NProgress.done(); // 关闭
    return Promise.reject(error);
  }
);

// Add a response interceptor
// 全局响应拦截
instance.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    NProgress.done();
    return response;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    NProgress.done();
    return Promise.reject(error);
  }
);

/**
 * 发起get请求
 * @param url
 * @param params
 * @returns
 */
export const get = (url: string, params = {}) =>
  instance.get(url, { params }).then((res) => res.data);
/**
 * 发起post请求
 * @param url
 * @param data
 * @returns
 */
export const post = (url: string, data = {}) =>
  instance.post(url, data).then((res) => res.data);

/**
 * 发起put请求
 * @param url
 * @param data
 * @returns
 */
export const put = (url: string, data = {}) =>
  instance.put(url, data).then((res) => res.data);

// 另一种请求方式和put做的是一样的事情
/**
 * 发起patch请求
 * @param url
 * @param data
 * @returns
 */
export const patch = (url: string, data = {}) =>
  instance.patch(url, data).then((res) => res.data);

/**
 * 发起delete请求
 * @param url
 * @returns
 */
export const del = (url: string) =>
  instance.delete(url).then((res) => res.data);
